package test12;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.*;
import java.util.*;

public class TestMain {
    public static void main(String[] args) {
        SeleSql1(ConnDB(),"select empno,ename,job,sal,dname from emp,dept where emp.deptno=dept.deptno");

    }

    public static Connection ConnDB() {
        try {
            //指定jdbc驱动类的路径，可以不写
            Class.forName("oracle.jdbc.driver.OracleDriver");

            String connStr = "jdbc:oracle:thin:@localhost:1521:XE";
            String userName = "scott";
            String password = "a123456";
            //创建一个数据库连接
            Connection conn = DriverManager.getConnection(connStr, userName, password);
            return conn;
        } catch (Exception throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    //查询语句,无返回值
    public static void SeleSql1(Connection conn, String seleStr) {
        try (
                //创建一个查询器
                Statement statement = conn.createStatement();
                //执行Sql语句  ，返回一个resultSet对象
                ResultSet resultSet = statement.executeQuery(seleStr);
        ) {
            if (resultSet != null) {
                //创建一个动态数据集，利用它可以得到数据集中数据表的各种信息
                ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
                for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
                    System.out.print(resultSetMetaData.getColumnName(i) + "        ");
                }
                System.out.println();
                while (resultSet.next()) {
                    for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
                        System.out.print(resultSet.getObject(i) + "      ");
                    }
                    System.out.println();
                }
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    //删除语句
    public static void DelSql(Connection conn, String name) {
        //  ? 占位符
        String delStr = "delete from emp where ename = ?";
        int count = 0;
        try {
            PreparedStatement preparedStatement = conn.prepareStatement(delStr);
            //给占位符传值，下标从一开始
            preparedStatement.setString(1, name);
            count = preparedStatement.executeUpdate();
            if (count > 0) {
                System.out.println("删除成功！");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
